package com.chinanet.utils.telnet;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ITelnet {
    protected TelnetClient telnet = new TelnetClient();
    protected InputStream in;
    protected PrintStream out;
    protected String prompt;
    protected Map<String, String> template;
    protected String mode;
    protected String matching;
    protected String username;
    protected String password;
    protected String ip;
    protected int port;

    public ITelnet(String ip, int port, String username, String password) {
        this.username = username;
        this.password = password;
        this.ip = ip;
        this.port = port;
        init();
    }

    public Map<String, String> getTemplate() {
        return template;
    }

    public void setTemplate(Map<String, String> template) {
        this.template = template;
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public String getMatching() {
        return matching;
    }

    public void setMatching(String matching) {
        this.matching = matching;
    }

    public TelnetClient getTelnet() {
        return telnet;
    }

    public void setTelnet(TelnetClient telnet) {
        this.telnet = telnet;
    }

    public InputStream getIn() {
        return in;
    }

    public void setIn(InputStream in) {
        this.in = in;
    }

    public PrintStream getOut() {
        return out;
    }

    public void setOut(PrintStream out) {
        this.out = out;
    }

    public String getPrompt() {
        return prompt;
    }

    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }

    public void init() {
        try {
            telnet.connect(ip, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        in = telnet.getInputStream();
        out = new PrintStream(telnet.getOutputStream());
    }

    /**
     * 登录
     *
     * @param prompt
     */
    public void login(String prompt) {
        this.prompt = prompt;
        readUntil("login:");
        write(username);
        readUntil("Password:");
        write(password);
        readUntil(this.prompt + "");
    }

    /**
     * 读取分析结果
     *
     * @param pattern
     * @return
     */
    public String readUntil(String pattern) {
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);
            StringBuffer sb = new StringBuffer();
            char ch = (char) in.read();

            while (true) {
                sb.append(ch);
                if (ch == lastChar) {
                    if (sb.toString().endsWith(pattern)) {
                        return sb.toString();
                    }
                }
                ch = (char) in.read();
//              System.out.print(ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String readUntil() {
        try {
            StringBuffer sb = new StringBuffer();
            char ch = (char) in.read();
            while (true) {
                sb.append(ch);
                System.out.print(ch);
                if ((int) ch == -1) {
                    byte[] temp = sb.toString().getBytes("iso8859-1");
                    String str = new String(temp, "UTF-8");
                }
                ch = (char) in.read();
                // System.out.print(ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取分析结果
     *
     * @param pattern
     * @return
     */
    public String readUntilByGET(String pattern) {
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);
            StringBuffer sb = new StringBuffer();
            char ch = (char) in.read();
            while (true) {
                sb.append(ch);
                if (ch == lastChar) {
                    byte[] temp = sb.toString().getBytes("iso8859-1");
                    String str = new String(temp, "utf-8");
                    if (str.endsWith(pattern)) {
                        return str;
                    }
                }
                ch = (char) in.read();
                // System.out.print(ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写操作
     *
     * @param value
     */
    public void write(String value) {
        try {
            out.println(value);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向目标发送命令字符串
     *
     * @param command
     * @return
     */
    public String sendCommand(String command) {
        try {
            write(command);
            return readUntil();
            //  return readUntil(prompt + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String sendCommand(String command, String decide) {
        try {
            write(command);
            return readUntil(decide);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        try {
            telnet.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String[] REGEX = new String[4];
        REGEX[0] = "+8657688910054";
        REGEX[1] = "88910054";
        REGEX[2] = "57688910054";
        REGEX[3] = "057688910054";
        for (int i = 0; i < REGEX.length; i++) {
            System.out.println(getInputPhoneFormat(REGEX[i]));
        }
    }

    public static Map<String, Object> matching(String regx, String str) {
        Map<String, Object> result = new HashMap<>();
        // 按指定模式在字符串查找
        String pattern = regx;
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        List<String> list = new ArrayList<>();
        while (m.find()) {
            list.add(m.group());
        }
        list.forEach(e -> {
            String str1 = e;
            if (str1.split("\\|=\\|").length >= 2) {
                result.put(str1.split("\\|=\\|")[0].trim(), str1.split("\\|=\\|")[1].trim());
            } else {
                result.put(str1.split("\\|=\\|")[0].trim(), "null");
            }
        });
        return result;
    }

    public static Map<String, Object> matchingTable(String regx, String str) {
        Map<String, Object> result = new HashMap<>();
        // 按指定模式在字符串查找
        String pattern = regx;
        StringBuilder sb = new StringBuilder();
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        List<String> list = new ArrayList<>();
        while (m.find()) {
            list.add(m.group());
        }
        list.forEach(e -> {
            sb.append(e);
        });
        result.put("result", sb.toString());
        return result;
    }

    public static String getInputPhoneFormat(String phoneName) {
        String replacement = "tel:+86576";
        if (!phoneName.startsWith(replacement)) {
            return replacement + phoneName.substring(phoneName.length() - 8, phoneName.length());
        } else {
            return phoneName;
        }
    }
}